package com.yaowk.web.system.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configurable
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${yaowk.security.antMatchers.permissAll:}")
    private String permissAll; // 注入配置不经过权限拦截的路径

    @Autowired
    private UserDetailsService userInfoService;
    @Autowired
    private SystemSecurityFilter systemSecurityFilter;
    @Autowired
    private SecurityAuthenticationRestHandler restHandler;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(4);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userInfoService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.addFilterAfter(systemSecurityFilter, FilterSecurityInterceptor.class);

        // 初始化不拦截的请求
        String[] permissAllArray = new String[]{"/*", "/static/**", "/webjars/**", "/swagger**", "/swagger-resources/**", "/v2/api-docs","/css/**","/js/**","/img/**","/layui/**"};
        if (!StringUtils.isEmpty(permissAll)) {
            List<String> permissList = new ArrayList<>(Arrays.asList(permissAllArray));
            permissList.addAll(Arrays.asList(permissAll.split(",")));

            permissAllArray = permissList.toArray(permissAllArray);
        }

        http.authorizeRequests()
                .antMatchers(permissAllArray).permitAll()
                .anyRequest().authenticated()

                // 登陆 成功/失败 后的处理，因为是API的形式所以不用跳转页面
                .and().formLogin().loginPage("/auth/login").successHandler(restHandler).failureHandler(restHandler).permitAll()
                // 登出后的处理
                .and().logout().logoutUrl("/auth/logout").logoutSuccessHandler(restHandler)
                // 认证不通过后的处理
                .and().exceptionHandling().authenticationEntryPoint(restHandler)
                .and().rememberMe();

    }
}
